package gateway.mgt.api

import gateway.auth.OAuthClientDetails
import groovy.transform.ToString

/**
 * Authentication & Authorization
 */
@ToString(includePackage = false, includes = ["name", "clientId"])
class ApiAuth {

    String name
    String description

    String clientId
    String clientSecret

    Date dateCreated
    Date lastUpdated

    static hasMany = [apiDefinitions: ApiDefinition]

    static constraints = {
        name(blank: false, unique: true)
        description(nullable: true, maxSize: 200, widget: 'textarea')
        clientId(nullable: false, unique: true, bindable: false)
        clientSecret(nullable: false, bindable: false)
        apiDefinitions(nullable: true)
        dateCreated()
        lastUpdated()
    }

    def beforeValidate() {
        clientId = new Date().format("ddMMyyHHmmss")
        clientSecret = UUID.randomUUID() as String
    }

    def beforeInsert() {
        OAuthClientDetails.withTransaction {
            return OAuthClientDetails.findByClientId(clientId) == null
        }
    }

    def afterInsert() {
        OAuthClientDetails.withTransaction {
            new OAuthClientDetails(clientId: clientId, clientSecret: clientSecret, authorities: "ApiAuth#" + id).save(flush: true)
        }
    }

    def beforeDelete() {
        OAuthClientDetails.withTransaction {
            return OAuthClientDetails.executeUpdate("delete OAuthClientDetails where clientId=:clientId", [clientId: clientId]) == 1
        }
    }
}
